package com.kurt.controller;

import com.kurt.annotation.Log;
import com.kurt.common.PageResult;
import com.kurt.common.Result;
import com.kurt.dto.DataPermissionDTO;
import com.kurt.dto.create.DataPermissionCreateRequest;
import com.kurt.dto.query.DataPermissionQueryRequest;
import com.kurt.service.DataPermissionService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 数据权限管理控制器
 * 提供数据权限相关的REST API接口
 */
@Slf4j
@RestController
@RequestMapping("/data-permissions")
@RequiredArgsConstructor
public class DataPermissionController extends BaseController {

    private final DataPermissionService dataPermissionService;

    /**
     * 创建数据权限
     *
     * @param createRequest 创建请求
     * @return 创建结果
     */
    @Log(title = "创建数据权限", businessType = 1)
    @PostMapping
    public Result<DataPermissionDTO> createDataPermission(@Valid @RequestBody DataPermissionCreateRequest createRequest) {
        try {
            log.info("创建数据权限请求: userId={}, entityTypeId={}, resourceId={}",
                    createRequest.getUserId(), createRequest.getEntityType(), createRequest.getResourceId());
            DataPermissionDTO dataPermission = dataPermissionService.createDataPermission(createRequest);
            return Result.success("数据权限创建成功", dataPermission);
        } catch (Exception e) {
            log.error("创建数据权限失败", e);
            return Result.error("创建数据权限失败: " + e.getMessage());
        }
    }


    /**
     * 根据ID获取数据权限详情
     *
     * @param id 权限ID
     * @return 数据权限详情
     */
    @GetMapping("/{id}")
    public Result<DataPermissionDTO> getDataPermissionById(@PathVariable("id") Long id) {
        try {
            log.info("获取数据权限详情请求: {}", id);
            DataPermissionDTO dataPermission = dataPermissionService.getDataPermissionById(id);
            return Result.success("获取数据权限详情成功", dataPermission);
        } catch (Exception e) {
            log.error("获取数据权限详情失败", e);
            return Result.error("获取数据权限详情失败: " + e.getMessage());
        }
    }

    /**
     * 分页查询数据权限
     *
     * @param queryRequest 查询请求
     * @return 分页结果
     */
    @PostMapping("/page")
    public Result<PageResult<DataPermissionDTO>> getDataPermissionPage(@RequestBody DataPermissionQueryRequest queryRequest) {
        try {
            log.info("分页查询数据权限请求: {}", queryRequest);
            Page<DataPermissionDTO> page = dataPermissionService.getDataPermissionPage(queryRequest);
            PageResult<DataPermissionDTO> pageResult = PageResult.of(
                    page.getNumber() + 1,
                    page.getSize(),
                    page.getTotalElements(),
                    page.getContent()
            );
            return Result.success("分页查询数据权限成功", pageResult);
        } catch (Exception e) {
            log.error("分页查询数据权限失败", e);
            return Result.error("分页查询数据权限失败: " + e.getMessage());
        }
    }

    /**
     * 查询数据权限列表
     *
     * @param queryRequest 查询请求
     * @return 数据权限列表
     */
    @PostMapping("/list")
    public Result<List<DataPermissionDTO>> getDataPermissionList(@RequestBody DataPermissionQueryRequest queryRequest) {
        try {
            log.info("查询数据权限列表请求: {}", queryRequest);
            List<DataPermissionDTO> dataPermissions = dataPermissionService.getDataPermissionList(queryRequest);
            return Result.success("查询数据权限列表成功", dataPermissions);
        } catch (Exception e) {
            log.error("查询数据权限列表失败", e);
            return Result.error("查询数据权限列表失败: " + e.getMessage());
        }
    }

    /**
     * 删除数据权限
     *
     * @param id 权限ID
     * @return 删除结果
     */
    @Log(title = "删除数据权限", businessType = 3)
    @DeleteMapping("/{id}")
    public Result<Boolean> deleteDataPermission(@PathVariable("id") Long id) {
        try {
            log.info("删除数据权限请求: {}", id);
            boolean success = dataPermissionService.deleteDataPermission(id);
            return Result.success("数据权限删除成功", success);
        } catch (Exception e) {
            log.error("删除数据权限失败", e);
            return Result.error("删除数据权限失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除数据权限
     *
     * @param ids 权限ID列表
     * @return 删除结果
     */
    @Log(title = "批量删除数据权限", businessType = 3)
    @DeleteMapping("/batch")
    public Result<Boolean> deleteDataPermissions(@RequestBody List<Long> ids) {
        try {
            log.info("批量删除数据权限请求: {}", ids);
            boolean success = dataPermissionService.deleteDataPermissions(ids);
            return Result.success("批量删除数据权限成功", success);
        } catch (Exception e) {
            log.error("批量删除数据权限失败", e);
            return Result.error("批量删除数据权限失败: " + e.getMessage());
        }
    }

    /**
     * 根据用户ID获取数据权限列表
     *
     * @param userId 用户ID
     * @return 数据权限列表
     */
    @GetMapping("/user/{userId}")
    public Result<List<DataPermissionDTO>> getDataPermissionsByUserId(@PathVariable("userId") Long userId) {
        try {
            log.info("根据用户ID获取数据权限列表请求: {}", userId);
            List<DataPermissionDTO> dataPermissions = dataPermissionService.getDataPermissionsByUserId(userId);
            return Result.success("获取数据权限列表成功", dataPermissions);
        } catch (Exception e) {
            log.error("获取数据权限列表失败", e);
            return Result.error("获取数据权限列表失败: " + e.getMessage());
        }
    }

    /**
     * 根据用户ID和实体类型获取数据权限列表
     *
     * @param userId       用户ID
     * @param entityTypeId 实体类型ID
     * @return 数据权限列表
     */
    @GetMapping("/user/{userId}/entity-type/{entityTypeId}")
    public Result<List<DataPermissionDTO>> getDataPermissionsByUserIdAndEntityType(
            @PathVariable("userId") Long userId,
            @PathVariable("entityTypeId") String entityTypeId) {
        try {
            log.info("根据用户ID和实体类型获取数据权限列表请求: userId={}, entityTypeId={}", userId, entityTypeId);
            List<DataPermissionDTO> dataPermissions = dataPermissionService.getDataPermissionsByUserIdAndEntityType(userId, entityTypeId);
            return Result.success("获取数据权限列表成功", dataPermissions);
        } catch (Exception e) {
            log.error("获取数据权限列表失败", e);
            return Result.error("获取数据权限列表失败: " + e.getMessage());
        }
    }

    /**
     * 检查用户是否有指定资源的权限
     *
     * @param userId       用户ID
     * @param entityTypeId 实体类型ID
     * @param resourceId   资源ID
     * @return 是否有权限
     */
    @GetMapping("/check")
    public Result<Boolean> hasPermission(@RequestParam Long userId,
                                         @RequestParam String entityTypeId,
                                         @RequestParam Long resourceId) {
        try {
            log.info("检查权限请求: userId={}, entityTypeId={}, resourceId={}",
                    userId, entityTypeId, resourceId);
            boolean hasPermission = dataPermissionService.hasPermission(userId, entityTypeId, resourceId);
            return Result.success("权限检查成功", hasPermission);
        } catch (Exception e) {
            log.error("权限检查失败", e);
            return Result.error("权限检查失败: " + e.getMessage());
        }
    }

    /**
     * 批量分配数据权限
     *
     * @param userId       用户ID
     * @param entityTypeId 实体类型ID
     * @param resourceIds  资源ID列表
     * @return 分配结果
     */
    @Log(title = "批量分配数据权限", businessType = 1)
    @PostMapping("/assign")
    public Result<Boolean> assignDataPermissions(@RequestParam Long userId,
                                                 @RequestParam String entityTypeId,
                                                 @RequestBody List<Long> resourceIds) {
        try {
            log.info("批量分配数据权限请求: userId={}, entityTypeId={}, resourceIds={}",
                    userId, entityTypeId, resourceIds);
            boolean success = dataPermissionService.assignDataPermissions(userId, entityTypeId, resourceIds);
            return Result.success("数据权限分配成功", success);
        } catch (Exception e) {
            log.error("数据权限分配失败", e);
            return Result.error("数据权限分配失败: " + e.getMessage());
        }
    }

    /**
     * 撤销数据权限
     *
     * @param userId       用户ID
     * @param entityTypeId 实体类型ID
     * @param resourceIds  资源ID列表
     * @return 撤销结果
     */
    @PostMapping("/revoke")
    @Log(title = "撤销数据权限", businessType = 3)
    public Result<Boolean> revokeDataPermissions(@RequestParam Long userId,
                                                 @RequestParam String entityTypeId,
                                                 @RequestBody List<Long> resourceIds) {
        try {
            log.info("撤销数据权限请求: userId={}, entityTypeId={}, resourceIds={}",
                    userId, entityTypeId, resourceIds);
            boolean success = dataPermissionService.revokeDataPermissions(userId, entityTypeId, resourceIds);
            return Result.success("数据权限撤销成功", success);
        } catch (Exception e) {
            log.error("数据权限撤销失败", e);
            return Result.error("数据权限撤销失败: " + e.getMessage());
        }
    }
}
